﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Alma.Core;
using Alma.Models;
using AlmaDatabase;
using System.Diagnostics;

namespace Alma.Controllers
{
    public class ShopController : Controller
    {
        public ActionResult Index()
        {
            using (var context = new AlmaDBEntities())
            {
                var shops = context.Shops;
                var list = from shop in shops
                           orderby shop.ID descending
                           select shop;
                return View(list.ToList());
            }
        }

        [Authorize]
        public ActionResult IndexByUserId(int userId = -1, int page = 0, int shopsPerPage = 10)
        {
            userId = (userId == -1 ? Int32.Parse(Session["UserId"].ToString()) : userId);
            using (var context = new AlmaDBEntities())
            {
                var shops = context.Shops;
                var list = from shop in shops
                           where (shop.ID_User != null &&
                                  shop.ID_User == userId)
                           orderby shop.ID
                           select shop;
                return View(list.Skip(page * shopsPerPage).Take(shopsPerPage).ToList());
            }
        }

        //
        // GET: /Shop/Details/5

        public ActionResult Details(int userId)
        {
            using (var context = new AlmaDBEntities())
            {
                var shop = from u in context.Shops
                           where u.ID_User == userId
                           select u;
                return View(shop.FirstOrDefault());
            }
        }

        //
        // GET: /Shop/Create

        [Authorize]
        public ActionResult Create(int userId = -1)
        {
            userId = (userId == -1 ? Int32.Parse(Session["UserId"].ToString()) : userId);
            var shopModel = new ShopModel
            {
                ID_User = userId,
            };
            return View(shopModel);
        }

        //
        // POST: /Shop/Create

        [HttpPost]
        public ActionResult Create(Shop newShop)
        {
            if (!ModelState.IsValid)
            {
                return View(new ShopModel(newShop));
            }
            using (var context = new AlmaDBEntities())
            {
                var req = BingMaps.Localize(newShop.Address, newShop.Town, newShop.Country);
                newShop.LocationX = req.X;
                newShop.LocationY = req.Y;
                context.Shops.AddObject(newShop);
                context.SaveChanges();
            }
            return RedirectToAction("Edit", "User", new { id = (long)Session["UserId"] });
        }

        //
        // GET: /Shop/Edit/5
        [Authorize]
        public ActionResult Edit(int id)
        {
            using (var context = new AlmaDBEntities())
            {
                var shop = from shops in context.Shops
                           where shops.ID == id
                           select shops;
                /* var usr = from usrs in context.Users select usrs;
                 List<string> list = usr.Select (c => c.Name).ToList ();
                 ViewData["drop"] = new SelectList(list);*/
                ShopModel shopModel = new ShopModel(shop.First());
                shopModel.Products = new List<ProductDetailsModel>();
                foreach (ProductDetailsModel pro in
                    (from p in context.Products where p.ID_Shop == id select p).Select(
                                                                                         product =>
                                                                                         new ProductDetailsModel
                                                                                         {
                                                                                             Name = product.Name,
                                                                                             ID = product.ID,
                                                                                             ImgUrl = product.ImgUrl ?? "~/Content/images/unavailable.gif"
                                                                                         }))
                {
                    shopModel.Products.Add(pro);
                }
                return View(shopModel);
            }
        }

        //
        // POST: /Shop/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, ShopModel newShop, string newLocationX, string newLocationY, bool useBing = false)
        {
            if (!ModelState.IsValid)
            {
                using (var context = new AlmaDBEntities())
                {
                    newShop.Products = new List<ProductDetailsModel>();
                    foreach (ProductDetailsModel pro in
                        (from p in context.Products where p.ID_Shop == id select p).Select(
                            product =>
                            new ProductDetailsModel
                                {
                                    Name = product.Name,
                                    ID = product.ID,
                                    ImgUrl =
                                        product.ImgUrl ??
                                        "~/Content/images/unavailable.gif"
                                }))
                    {
                        newShop.Products.Add(pro);
                    }
                }

                return View(newShop);

            }
            using (var context = new AlmaDBEntities())
            {
                var shops = from u in context.Shops
                            where u.ID == id
                            select u;
                var editShop = shops.First();
                editShop.Address = newShop.Address;
                editShop.Country = newShop.Country;
                editShop.Email = newShop.Email;
                editShop.Fax = newShop.Fax;
                editShop.Name = newShop.Name;
                editShop.Phone = newShop.Phone;
                editShop.Town = newShop.Town;
                editShop.Zipcode = newShop.Zipcode;
                editShop.Description = newShop.Description;
                editShop.ImgUrl = newShop.ImgUrl;

                if (useBing)
                {
                    var req = BingMaps.Localize(editShop.Address, editShop.Town, editShop.Country);
                    editShop.LocationX = req.X;
                    editShop.LocationY = req.Y;
                }
                else
                {
                    editShop.LocationX = double.Parse(newLocationX.Replace(',', '.'), CultureInfo.InvariantCulture);
                    editShop.LocationY = double.Parse(newLocationY.Replace(',', '.'), CultureInfo.InvariantCulture);
                }

                //var usr = from usrs in context.Users
                //          where usrs.Name == newShop.Name_User
                //          select usrs;
                //editShop.ID_User = usr.First().ID;
                context.SaveChanges();
            }
            return RedirectToAction("Edit", new { id = id });
        }

        //
        // GET: /Shop/Delete/5

        public ActionResult Delete(int id)
        {
            using (var context = new AlmaDBEntities())
            {
                var shop = from shops in context.Shops
                           where shops.ID == id
                           select shops;
                return View((shop.FirstOrDefault()));
            };
        }

        //
        // POST: /Shop/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, Shop delShop)
        {
            if (ModelState.IsValid)
            {
                using (var context = new AlmaDBEntities())
                {
                    var shop = from shops in context.Shops
                               where shops.ID == id
                               select shops;
                    context.Shops.DeleteObject(shop.FirstOrDefault());
                    context.SaveChanges();
                }
                return RedirectToAction("Edit", "User", new { id = (long)Session["UserId"] });
            }
            return View(delShop);
        }

        public ActionResult Show(int id)
        {
            ShopModel shopModel = new ShopModel();
            using (var entities = new AlmaDBEntities())
            {
                var shop = (from p in entities.Shops where p.ID == id select p).First();
                shopModel.ID = id;
                shopModel.ID_User = shop.ID_User;
                shopModel.Name = shop.Name;
                shopModel.Email = shop.Email;
                shopModel.Phone = shop.Phone;
                shopModel.Fax = shop.Fax;
                shopModel.Address = shop.Address;
                shopModel.Zipcode = shop.Zipcode;
                shopModel.Town = shop.Town;
                shopModel.Country = shop.Country;
                shopModel.Description = shop.Description;
                shopModel.LocationX = shop.LocationX;
                shopModel.LocationY = shop.LocationY;
                shopModel.ImgUrl = shop.ImgUrl;

                shopModel.Products = new List<ProductDetailsModel>();
                foreach (ProductDetailsModel pro in
                    (from p in entities.Products where p.ID_Shop == id select p).Select(
                                                                                         product =>
                                                                                         new ProductDetailsModel
                                                                                             {
                                                                                                 Name = product.Name,
                                                                                                 ID = product.ID,
                                                                                                 ImgUrl =
                                                                                                     product.ImgUrl ??
                                                                                                     "~/Content/images/unavailable.gif"
                                                                                             }))
                {
                    shopModel.Products.Add(pro);
                }
                /*reviews*/
                shopModel.reviews = new List<ProductReviewModel>();
                var comments = from reviewz in entities.T_Shop_Reviews
                               where reviewz.ID_Shop == shopModel.ID
                               select reviewz;
                int count = 0;
                int? totalScore = 0;
                foreach (var review in comments)
                {
                    ProductReviewModel model = new ProductReviewModel();
                    model.Text = review.Text;
                    var usr = from users in entities.Users
                              where review.ID_User == users.ID
                              select users;
                    model.Name_User = usr.First().Firstname;
                    model.Date = review.Date;
                    if (review.Score != null)
                    {
                        count++;
                        totalScore += review.Score;
                    }
                    shopModel.reviews.Add(model);
                    if (count != 0)
                        shopModel.score = (float)totalScore / (float)count;
                    else
                        shopModel.score = 0;
                }
                shopModel.reviews.Reverse();
            }
            List<int> list = new List<int>();
            for (int i = 1; i < 6; i++)
                list.Add(i);
            ViewData["drop"] = new SelectList(list);
            return View(shopModel);
        }

        public ActionResult AddReview(ProductDetailsModel p)
        {
            using (var context = new AlmaDBEntities())
            {
                T_Shop_Reviews rev = new T_Shop_Reviews();
                rev.Text = p.reviewText;
                try
                {
                    rev.ID_User = (long)Session["UserId"];
                }
                catch (Exception)
                {
                    return RedirectToAction("Connect", "User");
                }
                rev.ID_Shop = p.ID;
                rev.Date = DateTime.Now;
                if (p.reviewScore < 1)
                    p.reviewScore = 1;
                else if (p.reviewScore > 5)
                    p.reviewScore = 5;
                rev.Score = p.reviewScore;
                context.T_Shop_Reviews.AddObject(rev);
                context.SaveChanges();
            }
            return RedirectToAction("Show", new { id = p.ID });
        }
    }
}
